#!/usr/bin/python
#
# Copyright (C) Scott Walker 2007 <iswalker at gmail dot com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, write to:
# 	The Free Software Foundation, Inc.,
# 	51 Franklin Street, Fifth Floor
# 	Boston, MA  02110-1301, USA.
#

import os.path
from twisted.web import static, server
from btpdwebui import config, webui

# home dir and config initialization
if not os.path.exists(config.HOME_DIR):
    os.makedirs(config.HOME_DIR, mode=0700)
config.userconf.create_default()
config.userconf.load()

# set the template directory
webui.template.base_directory = config.TEMPLATE_DIR

# setup the twisted url handlers
root = static.File(config.STATIC_DIR)
root.putChild('login', webui.Login())
root.putChild('logout', webui.Logout())
root.putChild('torrents', webui.Torrents())
site = server.Site(root)

if __name__ == '__main__':
    # stand-alone twisted reactor application
    from twisted.internet import reactor
    reactor.listenTCP(int(config.userconf['port']), site)
    reactor.run()
else:
    # being run via the twistd daemon
    from twisted.application import internet, service
    application = service.Application('web')
    i = internet.TCPServer(int(config.userconf['port']), site)
    i.setServiceParent(service.IServiceCollection(application))

